const Service = require("egg").Service;

class UserService extends Service {
  // 获取用户列表
  async getUserList () {
    const { app } = this;
    try {
      return await app.model.User.findAll({
        attributes: ["id", "userName", "nickName","headPicture"],
        where: { delFlag: 0 },
        include: [
          {
            model: app.model.Role,
            attributes: ["id", "name",],
            through:{attributes:[]} //不查中间表
          }
        ],
      });
    } catch (err) {
      console.log(err);
      throw new Error(err)
    }
  }


  //模糊查询用户
  async getLikeUserList (userName,nickName) {
    const { app } = this;
    try {
      const where={}
      if (userName) {
        where['userName']={ $like: `%${userName}%` }
      }
      if (nickName) {
        where['nickName']={ $like: `%${nickName}%` }
      }
      return await app.model.User.findAll({
        attributes: ["id", "userName", "nickName","headPicture"],
        where: where,
        include: [
          {
            model: app.model.Role,
            attributes: ["id", "name",],
          }
        ],
      });
    } catch (err) {
      console.log(err);
      throw new Error(err)
    }
  }


  async modifyUser ({ id, userName, nickName ,headPicture }) {
    const { app } = this;
    try {
      if (!id) {
        return await app.model.User.create({
          userName,
          nickName,
          headPicture
        });
      } else {
        const exit = await app.model.User.findByPk(id);
        if (!exit) {
          this.ctx.logger.debug(`根据${id}无法查询到模板`);
          throw new Error("无法查询到模板");
        }
        exit.update({ userName, nickName,headPicture });
        return true;
      }
    } catch (err) {
      console.log(err);
      throw new Error(err)
    }
  }

  async saveUser ({ id, userName, nickName,headPicture,account_id }) {
    const { app } = this;
    try {
      if (!id) {
        return await app.model.User.create({
          userName,
          nickName,
          headPicture:headPicture,    
          account_id
        });
      } else {
        const exit = await app.model.User.findByPk(id);
        if (!exit) {
          this.ctx.logger.debug(`根据${id}无法查询到模板`);
          throw new Error("无法查询到模板");
        }
        exit.update({ userName, nickName,account_id });
        return true;
      }
    } catch (err) {
      console.log(err);
      throw new Error(err)
    }
  }

  async findUserById (id) {
    const { app } = this;
    try {
      return await app.model.User.findOne({
        where: { id },
      });
    } catch (err) {
      console.log(err);
      throw new Error(err)
    }
  }

  async findUserByAccount (id) {
    const { app } = this;
    try {
      return await app.model.User.findOne({
        where: { account_id:id },
      });
    } catch (err) {
      console.log(err);
      throw new Error(err)
    }
  }

  async findUserByUserName ({userName}) {
    const { app } = this;
    try {
      return await app.model.User.findOne({
        where: { userName },
      });
    } catch (err) {
      console.log(err);
      throw new Error(err)
    }
  }

  async deleteUser (id) {
    const { app } = this;
    try {
      const exit = await app.model.User.findByPk(id);
      if (!exit) {
        this.ctx.logger.debug(`根据${id}无法查询到模板`);
        throw new Error("无法查询到模板");
      }
      exit.update({ delFlag: 1 });
      return true;
    } catch (err) {
      console.log(err);
      throw new Error(err)
    }
  }

  async findUserSelfRoles(userId){
    const { app } = this;
    try {
      return await app.model.UserRole.findAll({
        attributes: ["id",  "userId","roleId" ],
        where: { userId: userId },
      });
    } catch (err) {
      console.log(err);
      throw new Error(err)
    }
  }

  async userAddRole(userId,roleIds){
    const { app } = this;
    try {
     const userRoles = await app.model.UserRole.findAll({
        attributes: ["id", "userId","roleId"],
        where: { userId: userId },
      });
      const userIds =userRoles.map(userRole=>userRole.userId)
      /**
       * 
       * 批量删除
       */
      let rows = await app.model.UserRole.destroy({
        where:{
          userId:userIds
        }
    })
     /**
      * 批量修改
      */
     let list=[]
     roleIds.forEach(roleId => {
      list.push({
        userId,roleId
      })
     });
      const exit = await app.model.UserRole.bulkCreate(list);
      return exit
    } catch (error) {
      throw new Error(error)
    }
    
  }

}

module.exports =UserService;
